package com.leyou.search.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.vo.PageResult;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.*;
import com.leyou.search.dto.GoodsDTO;
import com.leyou.search.dto.SearchRequest;
import com.leyou.search.pojo.Goods;
import com.leyou.search.respository.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SearchService {

    @Autowired
    private ItemClient itemClient;

    public Goods buildGoods(SpuDTO spu) {
        // 1.关键字搜索字段，包含名称、分类、品牌等等。。
        // 1.1.查询分类名称
        String categoryName = spu.getCategoryName();
        if (StringUtils.isBlank(categoryName)) {
            categoryName = itemClient.queryCategoryByIds(spu.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining());
        }
        // 1.2.查询品牌名称
        String brandName = spu.getBrandName();
        if (StringUtils.isBlank(brandName)) {
            brandName = itemClient.queryBrandById(spu.getBrandId()).getName();
        }
        // 1.3.拼接数据
        String all = spu.getName() + categoryName + brandName;

        // 2.spu下的sku的集合，转为json
        List<SkuDTO> skuDTOList = spu.getSkus();
        if (CollectionUtils.isEmpty(skuDTOList)) {
            skuDTOList = itemClient.querySkuBySpuId(spu.getId());
        }
        // 2.1.转换sku，保留四个必须字段
        List<Map<String, Object>> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", skuDTO.getId());
            map.put("title", skuDTO.getTitle());
            map.put("price", skuDTO.getPrice());
            map.put("image", StringUtils.substringBefore(skuDTO.getImages(), ","));
            skuList.add(map);
        }

        // 3.sku的价格的集合
        Set<Long> price = skuDTOList.stream().map(SkuDTO::getPrice).collect(Collectors.toSet());

        // 4.商品的规格参数对，key：规格参数名称，value：规格参数的值
        Map<String, Object> specs = new HashMap<>();
        // 4.1.查询规格参数key，当前商品所属分类下的searching为true的规格
        List<SpecParamDTO> specParams = itemClient.querySpecParams(null, spu.getCid3(), true);

        // 4.2.查询规格的值，查询spuDetail中的值
        SpuDetailDTO spuDetail = spu.getSpuDetail();
        if (spuDetail == null) {
            spuDetail = itemClient.querySpuDetailById(spu.getId());
        }
        // 4.2.1.获取通用规格的值
        Map<Long, Object> genericSpec = JsonUtils.toMap(spuDetail.getGenericSpec(), Long.class, Object.class);
        // 4.2.2.获取特有规格的值
        Map<Long, Object> specialSpec = JsonUtils.toMap(spuDetail.getSpecialSpec(), Long.class, Object.class);

        // 4.3.把规格参数key与规格参数值一一对应，然后put到specs的map中
        for (SpecParamDTO param : specParams) {
            // 取出参数名称，作为specs的key
            String key = param.getName();
            // 取出值，作为specs中的value
            Object value = param.getGeneric() ? genericSpec.get(param.getId()) : specialSpec.get(param.getId());

            // 判断value是否是数字，如果是，需要判断是在哪个分段，存储分段到value
            if (param.getNumeric()) {
                // 是数值，需要分段处理
                value = chooseSegment(value, param);
            }

            // 存入specs中
            specs.put(key, value);
        }

        // 5.创建Goods
        Goods goods = new Goods();
        // 填写数据到goods
        goods.setSubTitle(spu.getSubTitle());
        goods.setId(spu.getId());
        goods.setCategoryId(spu.getCid3());
        goods.setBrandId(spu.getBrandId());
        // 关键字搜索字段，包含名称、分类、品牌等
        goods.setAll(all);
        goods.setCreateTime(spu.getCreateTime().getTime());
        // sku的价格的集合
        goods.setPrice(price);
        // spu下的sku的集合，转为json
        goods.setSkus(JsonUtils.toString(skuList));
        // 商品的规格参数对，key：规格参数名称，value：规格参数的值
        goods.setSpecs(specs);
        return goods;
    }

    private String chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }

    @Autowired
    private ElasticsearchTemplate esTemplate;

    public PageResult<GoodsDTO> search(SearchRequest request) {
        String key = request.getKey();
        if (StringUtils.isBlank(key)) {
            // 请求参数为空，不查询数据，直接返回null。
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 1.初始化原生查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 2.编写查询条件
        // 2.1.source过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "skus", "subTitle"}, new String[0]));
        // 2.2.关键字搜索条件
        queryBuilder.withQuery(buildBasicQuery(request));
        // 2.3.分页
        int page = request.getPage() - 1;
        queryBuilder.withPageable(PageRequest.of(page, request.getSize()));
        // TODO 2.4.排序
        // queryBuilder.withSort(SortBuilders.fieldSort("price").order(SortOrder.ASC));

        // 3.搜索数据
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);

        // 4.解析结果
        // 4.1.解析分页结果
        long total = result.getTotalElements();
        int totalPage = result.getTotalPages();
        List<Goods> goodsList = result.getContent();
        // 4.2.转换DTO
        List<GoodsDTO> list = BeanHelper.copyWithCollection(goodsList, GoodsDTO.class);

        // 5.封装并返回
        return new PageResult<>(total, totalPage, list);
    }

    /**
     * 构建基本查询条件，搜索数据和过滤项的聚合，都应该使用这个条件
     *
     * @param request
     * @return
     */
    private QueryBuilder buildBasicQuery(SearchRequest request) {
        // 1.构建布尔查询
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        // 2.添加must查询，关键字搜索
        queryBuilder.must(QueryBuilders.matchQuery("all", request.getKey()));
        // 3.添加filter查询，用户点击的过滤项
        Map<String, String> filters = request.getFilter();
        // 遍历过滤项，逐个添加
        for (Map.Entry<String, String> entry : filters.entrySet()) {
            // 过滤项名称
            String key = entry.getKey();
            if ("分类".equals(key)) {
                key = "categoryId";
            } else if ("品牌".equals(key)) {
                key = "brandId";
            } else {
                key = "specs." + key;
            }
            // 以过滤项名称作为字段名，以值作为搜索条件，完成查询
            queryBuilder.filter(QueryBuilders.termQuery(key, entry.getValue()));
        }

        // 4.返回结果
        return queryBuilder;
    }

    public Map<String, List<?>> getFilters(SearchRequest request) {
        // 0.创建map，存放结果数据
        Map<String, List<?>> filters = new LinkedHashMap<>();

        String key = request.getKey();
        if (StringUtils.isBlank(key)) {
            // 请求参数为空，不查询数据，直接返回null。
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 1.初始化原生查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 2.搜索条件
        // 2.1.source过滤, 尽可能减少查询到的数据
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, new String[0]));
        // 2.2.关键字搜索条件
        queryBuilder.withQuery(buildBasicQuery(request));
        // 2.3.分页, 尽可能减少查询到的数据
        queryBuilder.withPageable(PageRequest.of(0, 1));
        // 2.4.添加聚合条件
        // 2.4.1.分类的聚合
        String categoryAgg = "categoryAgg";
        queryBuilder.addAggregation(AggregationBuilders.terms(categoryAgg).field("categoryId"));
        // 2.4.2.品牌的聚合
        String brandAgg = "brandAgg";
        queryBuilder.addAggregation(AggregationBuilders.terms(brandAgg).field("brandId"));

        // 3.搜索数据
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);

        // 4.解析结果
        Aggregations aggregations = result.getAggregations();

        // 4.1.处理分类聚合
        // 4.1.1.从聚合中获取分类id
        List<Long> categoryIds = getIdsFromAggregation(categoryAgg, aggregations);
        // 4.1.2.根据分类id查询分类
        List<CategoryDTO> categoryDTOList = itemClient.queryCategoryByIds(categoryIds);
        // 4.1.3.加入结果中
        filters.put("分类", categoryDTOList);

        // 4.2.处理品牌聚合
        // 4.2.1.从聚合中获取品牌id
        List<Long> brandIds = getIdsFromAggregation(brandAgg, aggregations);
        // 4.2.2.根据id查询品牌
        List<BrandDTO> brandDTOList = itemClient.queryBrandByIds(brandIds);
        // 4.2.3.加入结果中
        filters.put("品牌", brandDTOList);

        // 4.3.判断分类是否只剩下一个，决定要不要对规格参数聚合
        if (categoryIds != null && categoryIds.size() == 1) {
            // 对规格参数聚合，参数：分类id，查询的条件，结果的map
            handleSpecAggregation(categoryIds.get(0), request, filters);
        }

        // 5.封装并返回
        return filters;
    }

    private void handleSpecAggregation(Long cid, SearchRequest request, Map<String, List<?>> filters) {
        // 1.根据分类id，查询searching为true的规格参数
        List<SpecParamDTO> params = itemClient.querySpecParams(null, cid, true);

        // 2.初始化原生查询构建器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 3.添加查询和聚合条件
        // 3.1.source过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, new String[0]));
        // 3.2.查询条件
        queryBuilder.withQuery(buildBasicQuery(request));
        // 3.3.分页
        queryBuilder.withPageable(PageRequest.of(0, 1));
        // 3.4.添加聚合条件
        for (SpecParamDTO param : params) {
            // 获取参数的名称
            String name = param.getName();
            // 利用参数名作为聚合名称，利用"specs.参数名"作为聚合字段
            queryBuilder.addAggregation(AggregationBuilders.terms(name).field("specs." + name));
        }

        // 4.搜索数据
        AggregatedPage<Goods> result = esTemplate.queryForPage(queryBuilder.build(), Goods.class);

        // 5.解析结果
        Aggregations aggregations = result.getAggregations();

        for (SpecParamDTO param : params) {
            // 获取参数的名称，就是聚合名称
            String name = param.getName();
            // 根据聚合名称，获取聚合
            Terms terms = aggregations.get(name);
            // 获取桶中的结果
            List<String> list = terms.getBuckets()
                    .stream()
                    .map(Terms.Bucket::getKeyAsString)
                    // 过滤掉空的结果
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            // 封装结果
            filters.put(name, list);
        }

    }

    private List<Long> getIdsFromAggregation(String aggName, Aggregations aggregations) {
        // 4.1.根据聚合名称，获取聚合值
        Terms terms = aggregations.get(aggName);
        // 4.2.从terms中获取桶
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        // 4.3.处理桶，获取其中的id
        return buckets.stream()
                .map(bucket -> bucket.getKeyAsNumber().longValue())
                .collect(Collectors.toList());
    }

    @Autowired
    private GoodsRepository repository;

    public void addIndex(Long spuId) {
        // 查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);

        // 构建Goods
        Goods goods = buildGoods(spu);

        // 新增Goods
        repository.save(goods);
    }

    public void deleteIndex(Long spuId) {
        repository.deleteById(spuId);
    }
}
